<?php

namespace App\Http\Controllers;

use App\Order;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Log;

class PayController extends Controller
{
    public function pay(Request $request)
    {
        $data = $request->validate([
            'type' => 'required|in:0,1',
            'coins' => 'sometimes|required|onehundred',
            'vip' => 'sometimes|required|in:3,12',
            'paytype' => 'required|in:0,1',
        ]);
        $data['order'] = time();
        $data['user_id'] = request()->user()->id;
        if(!$data['type']){
            $data['money'] = $this->calculatemoney($data['coins']);
        }else if($data['vip'] == 3){
            $data['money'] = 9000;
        }else{
            $data['money'] = 29800;
        }
        //支付状态
        $data['status'] = 0;
        Order::create($data);

        if (request('paytype')) {
            return $this->wxpay($data);
        }
        return $this->alipay($data);
    }

    public function alipay($data)
    {
        $order = [
            'out_trade_no' => $data['order'],
            'total_amount' => number_format($data['money']/100,2),
//            'total_amount' => '0.01',
            'subject' => $data['type'] == 0 ? '交易币充值' : 'VIP充值',
        ];
        return Pay::alipay()->web($order);
    }

    public function wxpay($data)
    {
        $order = [
            'out_trade_no' => $data['order'],
            'body' => $data['type'] == 0 ? '交易币充值' : 'VIP充值',
            'total_fee' => $data['money'],
//            'total_fee' => '1',
        ];
        // 扫码支付使用 模式二
        $data = Pay::wechat()->scan($order);
        $data['out_trade_no'] = $order['out_trade_no'];
        return $data;
    }

    public function notify(Request $request)
    {
        $config = config('pay.alipay');
        $alipay = Pay::alipay($config);
        try {
            if ($alipay->verify() && $request->app_id == $config['app_id']) {
                $order = Order::where('order', $request->out_trade_no)->first();
                 if($order && $order->money == intval($request->total_amount*100)) {
                    if (!$order->status) {
                        $order->update(['status' => 1]);
                        $userinfo = User::find($order->user_id);
                        if ($order->type == 0) {
                            $userinfo->update(['coins' => $userinfo->coins + $order->coins,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过支付宝成功充值' . $order->coins . '交易币,感谢您的支持']));
                        } elseif ($userinfo->is_vip == 0) {
                            $vipduetime = Carbon::parse('+' . $order->vip . 'months')->toDateTimeString();
                            $userinfo->update(['is_vip' => 1, 'vipduetime' => $vipduetime,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过支付宝成功充值VIP会员，有效期至' . substr ( $vipduetime , 0 ,10) . '，感谢您的支持']));
                        } else {
                            $vipduetime = Carbon::parse($userinfo->vipduetime)->addmonth($order->vip);
                            $userinfo->update(['is_vip' => 1, 'vipduetime' => $vipduetime,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过支付宝成功续费VIP会员，有效期至' .substr($vipduetime,0,10 ) . '，感谢您的支持']));
                        }
                    }
                }
            }
            Log::debug('Alipay notify', $request->all());
        } catch (Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success()->send();
    }

    public function wxnotify(Request $request)
    {
        $config = config('pay.wechat');
        $wxpay = Pay::wechat($config);
        try {
            $data = $wxpay->verify(); // 是的，验签就这么简单！
            if ($data && $data['appid'] == $config['appid']) {
                $order = Order::where('order', $data['out_trade_no'])->first();
                if($order && $order->money == $data['total_fee']) {
                    if (!$order->status) {
                        $order->update(['status' => 1]);
                        $userinfo = User::find($order->user_id);
                        if ($order->type == 0) {
                            $userinfo->update(['coins' => $userinfo->coins + $order->coins,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过微信成功充值' . $order->coins . '交易币，感谢您的支持']));
                        } elseif ($userinfo->is_vip == 0) {
                            $vipduetime = Carbon::parse('+' . $order->vip . 'months')->toDateTimeString();
                            $userinfo->update(['is_vip' => 1, 'vipduetime' => $vipduetime,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过微信成功充值VIP会员，有效期至' . substr ( $vipduetime , 0 ,10). '，感谢您的支持']));
                        } else {
                            $vipduetime = Carbon::parse($userinfo->vipduetime)->addmonth($order->vip);
                            $userinfo->update(['is_vip' => 1, 'vipduetime' => $vipduetime,'upmoney'=> $userinfo->upmoney*100 + $order->money]);
                            $userinfo->notify(new \App\Notifications\Tixian(['message' => '您已通过微信成功续费VIP会员，有效期至' . substr ( $vipduetime , 0 ,10). '，感谢您的支持']));
                        }
                        Redis::setex($order->order, 600, 1);
                    }
                }
            }
        } catch (Exception $e) {
            // $e->getMessage();
        }

        return $wxpay->success()->send();
    }

    //计算金额
    public function calculatemoney($coins)
    {
        switch ($coins) {
            case ($coins < 100):
                $coins *= 100;
                break;
            case ($coins < 300):
                $coins *= 98;
                break;
            case ($coins < 500):
                $coins *= 96;
                break;
            case ($coins < 800):
                $coins *= 94;
                break;
            default:
                $coins *= 92;
                break;
        }
        return $coins;
    }

    public function wxreturn($order)
    {
        if (Redis::get($order)) {
            return response(['status' => 1, 'message' => 'success']);
        }else{
            return response(['status' => 0]);
        }
    }
}
